# -*- coding:utf-8 -*-
import os
import json
import re
from metlib.shell.fileutil import *

from .models import *


def update_all_mods():
    """更新所有可用的模块.

    :return:
    """
    mods_root = 'wrasmods'
    if mods_root is None:
        return
    folders = LS(mods_root)
    for modname in folders:
        try:
            config_fname = os.path.join(mods_root, modname, 'config')
            if not os.path.exists(config_fname):
                continue

            mod_conf = json.load(open(config_fname), strict=False)
            url_fname = os.path.join(mods_root, modname, 'urls.py')
            if os.path.exists(url_fname):
                mod_conf.setdefault('has_sub_url', True)

            info = mod_conf.pop('info', {})
            update_fields = mod_conf.keys()
            mod_model, created = WrasModule.objects.get_or_create(name=modname, defaults=mod_conf)
            if info:
                mod_model.info = info
                update_fields.append('info_json')
            mod_model.save(update_fields=update_fields)
        except Exception as e:
            print u"Error (%s)" % unicode(e)


def remove_poplayer_tokens(data, user_profile):
    old_tokens = user_profile.get_status('poplayer_tokens')
    to_remove = data.get('tokens', [])
    new_tokens = list(set(old_tokens) - set(to_remove))
    user_profile.set_status('poplayer_tokens', new_tokens)
    return new_tokens